package com.yy.wga.mp.module.file.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.yy.wga.common.core.exception.BusinessException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class OssUtils {
    private OssUtils() {
    }

    private final static String KEYED = "LTAI5t5d2ViCGS58bSGF4AVN";
    private final static String KEY = "DBZpl2mBuFwonq0bAyFAYvj1g8GKIn";
    /**
     * 阿里云访问路径这个是杭州的你要选择自己的
     */
    private final static String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
    /**
     * 这里填你自己的bucket
     */
    private final static String BUCKETNAME = "xianrcj";

    /**
     * springboot封装用于接受文件的对象
     *
     * @param file 传过来的数据
     * @return URL
     */
    public static String URL(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (Objects.nonNull(filename)) {
            String suffix = filename.substring(filename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();//生成不重复id;
            String objectName = uuid + suffix;
            OSS ossClient = new OSSClientBuilder().build(ENDPOINT, KEYED, KEY);//创建oss实例指定访问密钥
            try {
                PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, file.getInputStream());
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(file.getContentType());
                putObjectRequest.setMetadata(objectMetadata);
                ossClient.putObject(putObjectRequest);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return "https://" + BUCKETNAME + "." + ENDPOINT + "/" + objectName;//返回的URL
        }
        throw new BusinessException("上传图片错误");

    }
}